﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Rison.Web.Common;
using Rison.BusinessFacade.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Entity.Biz;
using Rison.BusinessFacade.Facade.Biz;
using Rison.Web.MobileService;


namespace Rison.Web.wysq
{
    public partial class SQContent : PageBase
    {

        #region "  page init  "
        protected void Page_Init(object sender, EventArgs e)
        {
            this.FileUpload1.AutoLoadAttachment = false;
            this.FileUpload1.ParentKeyName = "RequestId";
            this.FileUpload1.AttachmentTablename = "UploadFile";
            this.FileUpload1.UploadFolder = "\\File\\Upload\\wysq\\";
        }
        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.labSize.Text = GlobalParams.Instance.maxAttachmentSize.ToString();
                this.btnSubmit.Attributes.Add("OnClick", "javascript:return window.confirm('您确认信息已填写完毕并提交吗？');");

                InitData();
            }

            AppendStyle();
        }


        #region "  初始下拉框数据  "
        private void InitData()
        {
            DataSourceHelperFacade facade = new DataSourceHelperFacade(InfoCategory.我有诉求);

            DataSet data = facade.GetDepartments();
            this.drpDepartment.DataSource = data.Tables[0].DefaultView;//部门
            this.drpDepartment.DataValueField = "bmid";
            this.drpDepartment.DataTextField = "bmmc";
            this.drpDepartment.DataBind();
            this.drpDepartment.Items.Insert(0, new ListItem("--请选择--", "0"));

            //data = facade.GetSQCategory();
            //this.rblSQFL.DataSource = data.Tables[0].DefaultView;
            //this.rblSQFL.DataValueField = "SQLB";
            //this.rblSQFL.DataTextField = "SQLB";
            //this.rblSQFL.DataBind();
            //只有三类，没有建议类型，故删除之 -- xj 2011/3/28
            if (rblSQFL.Items.FindByText("投诉") == null)
                this.rblSQFL.Items.Add(new ListItem("投诉", "投诉"));
            //if (rblSQFL.Items.FindByText("建议") == null)
            //    this.rblSQFL.Items.Add(new ListItem("建议", "建议"));
            if (rblSQFL.Items.FindByText("咨询") == null)
                this.rblSQFL.Items.Add(new ListItem("咨询", "咨询"));


            //data = facade.GetSQCategory();
            //this.drpSQLB.DataSource = data.Tables[0].DefaultView;//诉求类别
            //this.drpSQLB.DataValueField = "SQLB";
            //this.drpSQLB.DataTextField = "SQLB";
            //this.drpSQLB.DataBind();            
            //this.drpSQLB.Items.Insert(0, new ListItem("--请选择--", "0"));

            data.Dispose(); data = null; facade = null;
        }

        private void AppendStyle()
        {
            foreach (ListItem item in rblSQFL.Items)
            {
                item.Attributes.CssStyle.Add("color", "#4b4b4b");
                item.Attributes.CssStyle.Add("padding-right", "20px");
            }
        }
        #endregion



        protected void btnReset_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }


        #region "  验证输入的数据  "
        private bool ValiateInputData()
        {
            string msg = string.Empty;
            if (rblSQFL.SelectedIndex < 0 || rblSQFL.SelectedItem == null)
                msg = "请选择诉求分类！";
            else if (drpDepartment.SelectedIndex <= 0)
                msg = "请选择相关部门！";
            else if (StringHelper.IsNullOrEmpty(txtBT.Text))
                msg = "请输入标题！";
            else if (!StringHelper.ValidLength(txtBT.Text, 200))
                msg = "标题不能超过100个汉字！";
            else if (StringHelper.IsNullOrEmpty(txtZW.Text))
                msg = "请输入正文！";
            else if (!StringHelper.ValidLength(txtZW.Text, 4000))
                msg = "标题不能超过2000个汉字！";
            else if (!StringHelper.ValidLength(txtFJSM.Text, 400))
                msg = "附件说明不能超过200个汉字！";
            else if (StringHelper.IsNullOrEmpty(txtXM.Text))
                msg = "请输入您的姓名！";
            else if (StringHelper.IsNullOrEmpty(txtSJ.Text) && StringHelper.IsNullOrEmpty(txtEmail.Text) && StringHelper.IsNullOrEmpty(txtDH.Text))
                msg = "请至少输入电话、手机或邮箱中的一项！";
            else if (!StringHelper.ValidLength(txtEmail.Text, 50))
                msg = "邮箱不能超过50个字符！";
            else if (!StringHelper.ValidLength(txtXM.Text, 100))
                msg = "姓名不能超过50个汉字！";
            else if (!StringHelper.ValidLength(txtDH.Text, 30))
                msg = "电话不能超过30个字符！";
            else if (!StringHelper.ValidLength(txtSJ.Text, 20))
                msg = "手机不能超过20个字符！";
            else if (!StringHelper.ValidLength(txtTSDW.Text, 100))
                msg = "被投诉人（单位）不能超过50个汉字！";
            else if (!StringHelper.ValidLength(txtTSDZ.Text, 100))
                msg = "被投诉人（单位）地址不能超过50个汉字！";

            if (!string.IsNullOrEmpty(msg))
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('" + msg + "');</script>");

            return string.IsNullOrEmpty(msg);
        }
        #endregion


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (this.ucVerifyCode1.ValidateVerificationCode() == false)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('对不起，验证码错误！');</script>");
            }
            else if (ValiateInputData() == true)
            {
                MyAppeal appeal = new MyAppeal();
                appeal.Type = rblSQFL.SelectedValue;//诉求分类
                appeal.SendToTag = drpDepartment.SelectedValue;//收件人的部门guid
                appeal.SendToName = drpDepartment.SelectedItem.Text;//收件人的部门名称
                appeal.MailBoxID = drpDepartment.SelectedValue;
                appeal.CategoryMailboxRelID = string.Empty;
                appeal.Title = txtBT.Text.Trim();
                appeal.Content = txtZW.Text.Trim();
                appeal.BackNvarchar = this.chkGK.Checked;
                appeal.BackNvarchar2 = txtTSDW.Text.Trim();
                appeal.BackNvarchar3 = txtTSDZ.Text.Trim();

                Appealer u = new Appealer();
                u.Sender = txtXM.Text.Trim();
                u.Email = txtEmail.Text.Trim();
                u.Phone = txtDH.Text + " " + txtSJ.Text;
                u.Address = txtDWDZ.Text.Trim();
                u.ZipCode = string.Empty;//该字段将用来保存系统随机生成的用户诉求密码
                u.FromType = "来信";// rblSQFL.SelectedValue;

                DataSourceHelperFacade facade = new DataSourceHelperFacade(InfoCategory.我有诉求);
                bool success = facade.SaveMyAppeal(appeal, u, this.FileUpload1.Attachments, txtFJSM.Text.Trim());

                if (success)
                {
                    btnSubmit.Enabled = false; btnReset.Enabled = false;

                    string msg = "提交完成！感谢您对我们工作的支持！\\n\\n请记录下面的密码，查询您的诉求的处理结果。\\n\\n密码：" + appeal.Password;

                    string sendmessageFlag = SendMessage();
                    msg += sendmessageFlag;
                    

                    Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('" + msg + "');location.href='../default.aspx';</script>");
                    //Response.Redirect("../Default.aspx");
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('对不起，提交失败！可能是因为网络比较繁忙，请稍后再试...');</script>");
                }

            }


        }

        #region "短信"
        private string SendMessage()
        {
            MobileService.SMS sms = new MobileService.SMS();
            SMSSoapHeader header = new SMSSoapHeader();
            header.user = "kenew";
            header.Password = "4ba5e552-53ff-4ed0-b868-40594db2f096";
            sms.SMSSoapHeaderValue = header;

            string context ="您有一份新的诉求待审批：" + this.txtBT.Text;
            string result="";
            string msg = "";
            int unsucc = 0;
            //int i = GlobalParams.Instance.mobileNumber.Count;

            for (int i = 0; i < GlobalParams.Instance.mobileNumber.Count; i++)
            {
                result = sms.SendMessage(GlobalParams.Instance.mobileNumber[i].ToString().Trim(), context);
                try
                {
                    Guid id = new Guid(result);
                }
                catch
                {
                    unsucc = unsucc + 1;
                }
            }

            if (unsucc > 0)
                msg = "\\n\\n" + unsucc.ToString() + "条短信发送失败！" + (GlobalParams.Instance.mobileNumber.Count - unsucc).ToString() + "条短信发送成功！";
            else
                msg = "\\n\\n" + GlobalParams.Instance.mobileNumber.Count.ToString() + "条短信发送成功！";

            return msg;
        }

        #endregion

    }
}
